package com.huawei.hmsdemo10086.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.huawei.hmsdemo10086.POJO.Order;
import com.huawei.hmsdemo10086.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderAdapter extends BaseAdapter {

    private List<Order> datas = new ArrayList<Order>();


    private Context context;
    private LayoutInflater layoutInflater;

    public OrderAdapter(Context context, List<Order> datas) {
        this.datas = datas;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return datas.size(); //返回列表的长度
    }

    @Override
    public Order getItem(int position) {
        return datas.get(position); //通过列表的位置 获得集合中的对象
    }

    @Override
    public long getItemId(int position) { // 获得集合的Item的位置
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.layout_order_node, null);//找到布局文件
            convertView.setTag(new ViewHolder(convertView));
        }
        initViews(getItem(position), (ViewHolder) convertView.getTag());
        return convertView;

    }

    private void initViews(Order data, ViewHolder holder) {//初始化数据

        /**
         * 第一次初始话的时候通过 要请求的Url地址 为每个图片设置一个Tag标记,
         * 然后在设置图片的时候判断Tag标记如果是才把图片设置到ImageView上,
         * 这做的原因是为了防止ListView 中的图片错位...
         */
        System.out.println("111");

        holder.num.setText(""+data.getNum());//设置Tag

        //设置新闻标题为集合中获得的标题
        holder.title.setText(data.getGoods().getName());


        holder.price.setText(""+data.getGoods().getPrice() * data.getNum());

        RoundedCorners roundedCorners = new RoundedCorners(20);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).skipMemoryCache(true);

        Glide.with(context)
                .load(data.getGoods().getPicaddress())
                .apply(options)
                .into(holder.img);


        Log.d("orderInfo", data.getGoods().getGoodsid()+"/"+data.getOrderid());


        switch (data.getStatus()){
            case 0://发货
                holder.order_status.setText("待发货");
                holder.delete_order.setVisibility(View.GONE);
                holder.confirm_order.setVisibility(View.VISIBLE);
                holder.apply_back.setVisibility(View.VISIBLE);
                break;
            case 1://确认收货
                holder.delete_order.setVisibility(View.VISIBLE);
                holder.order_status.setText("已收货");
                holder.confirm_order.setVisibility(View.GONE);
                break;
            case 2://退货
                holder.order_status.setText("退款申请中");
                holder.apply_back.setText("申请中");
                holder.confirm_order.setVisibility(View.GONE);
                holder.delete_order.setVisibility(View.GONE);
                break;
        }

        holder.delete_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/deleteOrder";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"orderid\": \"" + data.getOrderid() + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                    }
                });
                datas.remove(data);
                notifyDataSetChanged();
            }
        });

        holder.confirm_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/changeStatus";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"status\": \"" + 1 + "\",\n" +
                        "  \"orderid\": \"" + data.getOrderid() + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        holder.order_status.setText("已收货");

                    }
                });
                holder.delete_order.setVisibility(View.VISIBLE);
                holder.order_status.setText("已收货");
                holder.confirm_order.setVisibility(View.GONE);

            }
        });

        holder.apply_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://10.0.2.2:8443/api/changeStatus";
                OkHttpClient mOkHttpClient = new OkHttpClient();

                Log.d("orderInfo", data.getGoodsid()+"/"+data.getOrderid());

                String json = "{\n" +
                        "  \"goodsid\": \"" + data.getGoodsid() + "\",\n" +
                        "  \"status\": \"" + 2 + "\",\n" +
                        "  \"orderid\": \"" + data.getOrderid() + "\"\n" +
                        "}";

                Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"),json)).build();

                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("测试", e+"");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                    }
                });

                holder.order_status.setText("退款申请中");
                holder.apply_back.setText("申请中");
                holder.confirm_order.setVisibility(View.GONE);
                holder.delete_order.setVisibility(View.GONE);

            }
        });



    }

    protected class ViewHolder {
        private TextView price;
        private TextView title;
        private TextView num;
        private ImageView img;
        private Button delete_order;
        private Button confirm_order;
        private Button apply_back;
        private TextView order_status;


        public ViewHolder(View view) {
            title = (TextView) view.findViewById(R.id.goods_title);
            num = (TextView) view.findViewById(R.id.goods_num);
            price = (TextView) view.findViewById(R.id.goods_price);
            img = view.findViewById(R.id.order_item_img);
            delete_order = (Button)view.findViewById(R.id.delete_order);
            confirm_order = (Button)view.findViewById(R.id.confirm_order);
            apply_back = (Button)view.findViewById(R.id.apply_back);
            order_status = (TextView)view.findViewById(R.id.order_status);

        }
    }

//    public void getImage(Context context, String imgUrl,
//                         final ImageView imageView) {
//
//        /**
//         * 检测图片的Tag值 ,如果根请求的地址相同 才做图片的网络请求.
//         */
//        if (imageView.getTag().toString().equals(imgUrl)) {
//            RequestQueue mQueue = Volley.newRequestQueue(context);
//            ImageRequest imageRequest = new ImageRequest(imgUrl,
//                    new Response.Listener<Bitmap>() {
//                        @Override
//                        public void onResponse(Bitmap response) {
//                            Bitmap outBitmap = RoundRectImageView.getRoundBitmapByShader(response, 500,300,10, 0);
//                            imageView.setImageBitmap(outBitmap);//将返回的Bitmap显示子啊ImageView上
//                        }
//                    }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
//                @Override
//                public void onErrorResponse(VolleyError error) {
//                }
//            });
//            mQueue.add(imageRequest);
//        }
//    }
}
